package com.example.controller;

import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 管理员前端操作接口
 **/
@RestController
@RequestMapping("/User")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.registerForUser(user);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        userService.deleteById(id);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result updateByUId(@RequestBody User user) {
        userService.updateByUId(user);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.selectById(id);
        return Result.success(user);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<User> page = userService.selectPage(pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 头像上传
     */
    @PostMapping("/UserAvatar/update")
    public Result updateUserAvatar(@RequestParam("uid") Integer uid, @RequestParam("file") MultipartFile file) throws IOException {
        try {
            System.out.println("接收到的Uid: "+ uid);
            System.out.println("接收到的文件名: " + file.getOriginalFilename());

            return userService.uploadUserAvatar(uid, file);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.Response(500, "头像更新失败", null);
        }
    }


}